# -*- coding:utf-8 -*-
import sys
import os.path
import arcpy
from datetime import datetime
import argparse

# 获取当前脚本所在目录的父目录
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)
from utils.utools import check_lock_with_testschemalock

def landslidePolygon2Raster(fc_study_area, fc_landslide, out_raster_fullPath, cell_size=30, val_landslide=1, val_notlandslide=0):

    # 检查fc_landslide是否被锁定了
    check_lock_with_testschemalock(fc_landslide)

    now_str = datetime.now().strftime('%Y%m%d%H%M')
    y_field_name = "y_{0}".format(now_str)
    fc_symdiff = "tmp_symdiff_{0}".format(now_str)
    fc_merge = "tmp_merge_{0}".format(now_str)

    # delete exist temporary feature class
    if arcpy.Exists(fc_symdiff):
        arcpy.Delete_management(fc_symdiff)
    if arcpy.Exists(fc_merge):
        arcpy.Delete_management(fc_merge)
    if arcpy.Exists(out_raster_fullPath):
        arcpy.Delete_management(out_raster_fullPath)
    try:
        #---------------------------------------------------
        arcpy.analysis.SymDiff(fc_study_area, fc_landslide, fc_symdiff, "NO_FID", None)

        arcpy.management.AddField(fc_symdiff, y_field_name, "LONG", None, None, None, y_field_name,
                                  "NULLABLE", "NON_REQUIRED", None)

        non_landslide_exp = "{0}".format(val_notlandslide)
        arcpy.CalculateField_management(in_table=fc_symdiff,
                                        field=y_field_name,
                                        expression=non_landslide_exp,
                                        expression_type="PYTHON")

        #---由于fc_landslide可能已经加载到ArcMap中被锁定了，因此先将fc_landslide复制一份-------------------
        fc_landslide_layer_name = os.path.basename(fc_landslide)
        copyed_fc_landslide = '{}copyed'.format(fc_landslide_layer_name)
        in_fc_dir = os.path.dirname(fc_landslide)
        copyed_fc_landslide = os.path.join(in_fc_dir, copyed_fc_landslide)
        arcpy.CopyFeatures_management(fc_landslide, copyed_fc_landslide)

        # 给复制的滑坡面添加字段：y_field_name
        result_landslide_add = arcpy.management.AddField(copyed_fc_landslide, y_field_name, "LONG", None, None, None, y_field_name,
                                                         "NULLABLE", "NON_REQUIRED", None)
        arcpy.AddMessage('给{}添加字段{}成功!'.format(copyed_fc_landslide, y_field_name))


        landslide_exp = "{0}".format(val_landslide)
        arcpy.CalculateField_management(in_table=copyed_fc_landslide,
                                        field=y_field_name,
                                        expression=landslide_exp,
                                        expression_type="PYTHON")


        fieldMappings = arcpy.FieldMappings()

        fldMap = arcpy.FieldMap()
        fldMap.mergeRule = 'Last'
        fldMap.addInputField(fc_symdiff, y_field_name)
        fldMap.addInputField(copyed_fc_landslide, y_field_name)

        label_name = fldMap.outputField
        label_name.name = y_field_name
        fldMap.outputField = label_name

        fieldMappings.addFieldMap(fldMap)

        result_merge = arcpy.Merge_management([fc_symdiff, copyed_fc_landslide], fc_merge, fieldMappings)

        #----------------------------------------------------
        y_val_field = y_field_name
        result_cov = arcpy.conversion.PolygonToRaster(fc_merge, y_val_field, out_raster_fullPath, "CELL_CENTER", "NONE", cell_size)

        if arcpy.Exists(fc_symdiff):
            arcpy.Delete_management(fc_symdiff)
        if arcpy.Exists(fc_merge):
            arcpy.Delete_management(fc_merge)
        if arcpy.Exists(copyed_fc_landslide):
            arcpy.Delete_management(copyed_fc_landslide)

    except Exception as e:
        arcpy.AddError("处理过程中发生错误:")
        arcpy.AddError(str(e))
        return None

def main():
    parser = argparse.ArgumentParser(description='滑坡面转栅格标签图层')
    # parser.add_argument('--workdir', required=True, help='工作空间')
    parser.add_argument('--fc_study_area', required=True, help='研究区面')
    parser.add_argument('--fc_landslide_polygon', required=True, help='输入的滑坡面')
    parser.add_argument('--out_raster_fullpath', required=True, help='输出栅格的完整路径')
    parser.add_argument('--cell_size', type=int, required=True, help='输出栅格大小')
    parser.add_argument('--val_landslide', type=int, required=True, help='滑坡的值')
    parser.add_argument('--val_notlandslide', type=int, required=True, help='非滑坡的值')
    args = parser.parse_args()
    cell_size = int(args.cell_size)
    val_landslide = int(args.val_landslide)
    val_notlandslide = int(args.val_notlandslide)

    arcpy.env.workspace = os.path.dirname(args.out_raster_fullpath)
    arcpy.env.overwriteOutput = True

    landslidePolygon2Raster(args.fc_study_area, args.fc_landslide_polygon, args.out_raster_fullpath,
                            cell_size=cell_size, val_landslide=val_landslide, val_notlandslide=val_notlandslide)

if __name__ == '__main__':
    main()


    # fc_study_area = arcpy.GetParameterAsText(0)
    # fc_landslide = arcpy.GetParameterAsText(1)
    # out_raster_fullPath = arcpy.GetParameterAsText(2)
    # cell_size = float(arcpy.GetParameterAsText(3))
    # val_landslide = float(arcpy.GetParameterAsText(4))
    # val_notlandslide = float(arcpy.GetParameterAsText(5))
    # landslidePolygon2Raster(fc_study_area, fc_landslide, out_raster_fullPath, cell_size=cell_size, val_landslide=val_landslide, val_notlandslide=val_notlandslide)